package com.z.platform.controller.persistence.orm;

import com.z.platform.controller.persistence.ConnectionFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Objects;
import java.util.concurrent.ConcurrentMap;

/**
 * @author 21051
 */
public abstract class AbstractDao implements Dao {

    protected JdbcConnectionModel getInsertPreparedStatement(String sql, ConcurrentMap<Integer, String> valueConcurrentMap, ConcurrentMap<Integer, String> typeConcurrentMap) {
        Connection conn = null;
        try {
            conn = ConnectionFactory.getConnection();
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            valueConcurrentMap.forEach((Integer key, String value) -> {
                try {
                    if (typeConcurrentMap.get(key).equals(String.class.getName())) {
                        preparedStatement.setString(key, value);
                    }
                    if (typeConcurrentMap.get(key).equals(Integer.class.getName()) || typeConcurrentMap.get(key).equals(int.class.getName())) {
                        preparedStatement.setInt(key, Integer.parseInt(value));
                    }
                    //todo 其他类型暂时不管了
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            });
            return new JdbcConnectionModel(preparedStatement, conn);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    protected void jdbcShoutDown(JdbcConnectionModel jdbcConnectionModel) {
        try {
            jdbcConnectionModel.getConnection().close();
            if (Objects.nonNull(jdbcConnectionModel.getPreparedStatement())) {
                jdbcConnectionModel.getPreparedStatement().close();
            }
            if (Objects.nonNull(jdbcConnectionModel.getStatement())) {
                jdbcConnectionModel.getStatement().close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


}
